const PENDING = 'pengding'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'

function MyPromise(fn) {
    const self = this

    self.state = PENDING
    self.value = null

    self.resolveCallBack = []
    self.rejectCallBack = []


    function resolve(value) {
        if(self.state === PENDING) {
            self.state = RESOLVED
            self.value = value
            self.resolveCallBack.forEach(cb => cb(value))
        }
    }

    function reject(value) {
        if(self.state === PENDING) {
            self.state = REJECTED
            self.value = value
            self.rejectCallBack.forEach(cb => cb(value))
        }
    }

    try{
        fn(resolve, reject)
    }catch(e) {
        reject(e)
    }
}

MyPromise.prototype.then = function (onFullFilled, onRejected) {
    const self = this
    onFullFilled = typeof onFullFilled === 'function' ? onFullFilled : v => v
    onRejected = typeof onRejected === 'function' ? onRejected: r => {
        throw r
    }
    console.log(self.state)
    self.resolveCallBack.push(onFullFilled)
    self.rejectCallBack.push(onRejected)
}

new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(123)
    }, 1e3);
}).then(res => {
    console.log(res)
})